package cn.com.service.impl;

import cn.com.Util.CopyUtils;
import cn.com.Util.StringUtil;
import cn.com.domain.BlockEntity;
import cn.com.domain.DocumentEntity;
import cn.com.domain.dto.DocumentDTO;
import cn.com.domain.vo.DocumentVo;
import cn.com.mapper.DocumentMapper;
import cn.com.response.BaseResponse;
import cn.com.response.BaseResponseStatus;
import cn.com.service.DocumentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @Author CRL
 * @Date 2021/4/27 21:20
 */
@Service
public class DocumentServiceImpl extends ServiceImpl<DocumentMapper, DocumentEntity> implements DocumentService {

    public static ArrayList<DocumentVo> blockchain = new ArrayList<DocumentVo>();
    public static int difficulty = 5;

    @Override
    public BaseResponse saveDocument(DocumentDTO requestDto) {
        DocumentEntity workDiaryEntity = new DocumentEntity();
        CopyUtils.copyProperties(requestDto, workDiaryEntity);
        String workContent = workDiaryEntity.getDocumentContent();
        addBlock(new DocumentVo(workContent, "0"));
        String blockchainJson = StringUtil.getJson(blockchain);
        workDiaryEntity.setNoobChain(blockchainJson);
        boolean save = this.save(workDiaryEntity);
        if (save) {
            return new BaseResponse(workDiaryEntity);
        } else {
            return new BaseResponse<>(BaseResponseStatus.FAILURE, "保存失败");
        }
    }

    @Override
    public BaseResponse findById(String id) {
        DocumentEntity serviceById = this.getById(id);
        return new BaseResponse(serviceById);
    }

    public void addBlock(DocumentVo newBlock) {
        newBlock.mineBlock(difficulty);
        blockchain.add(newBlock);
    }

    public static Boolean isChainValid() {
        DocumentVo currentBlock;
        String hashTarget = new String(new char[difficulty]).replace('\0', '0');
        //loop through blockchain to check hashes:
        for (int i = 1; i < blockchain.size(); i++) {
            currentBlock = blockchain.get(i);
            //compare registered hash and calculated hash:
            if (!currentBlock.hash.equals(currentBlock.calculateHash())) {
                System.out.println("Current Hashes not equal");
                return false;
            }
        }
        return true;
    }

}
